﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using WebCore.Helpers;
using System.Web.Security;

namespace WebCore.Attributes
{


    /// <summary>
    /// this custom attribute comes from 
    /// http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/
    /// </summary>
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        // the "new" must be used here because we are overriding
        // the Roles property on the underlying class
        public new WebRoles Roles;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            string[] users = Users.Split(',');

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            FormsIdentity formsIdentiy = ((FormsIdentity)httpContext.User.Identity);

            if (formsIdentiy == null)
                return false;

            string roleString = UserHelper.GetUserRoleFromIdentityTicket(formsIdentiy);

            if(string.IsNullOrEmpty(roleString))
                return false;

            // get the role
            WebRoles role = (WebRoles)Tools.StringToEnum(typeof(WebRoles), roleString);


            if (Roles != 0 && ((Roles & role) != role))
                return false;


            return true;
        }



    }


}




//public class CustomAuthorizeAttribute : AuthorizeAttribute
//{
//    // the “new” must be used here because we are overriding the Roles property on the underlying class
//    public new WebRoles Roles;

//    private bool FailedRolesAuth = false;

//    protected override bool AuthorizeCore(HttpContextBase httpContext)
//    {
//        if (httpContext == null)
//            throw new ArgumentNullException("httpContext");

//        if (!httpContext.User.Identity.IsAuthenticated)
//            return false;

//        string[] users = Users.Split(',');

//        if (users.Length > 0 && !users.Contains("test", StringComparer.OrdinalIgnoreCase))
//            return false;

//        if (httpContext.Session["role"] == null)
//            return false;

//        WebRoles role = (WebRoles)httpContext.Session["role"];

//        if (Roles != 0 && (Roles & role) != role)
//        {
//            FailedRolesAuth = true;
//            return false;
//        }

//        return true;
//    }

//    public override void OnAuthorization(AuthorizationContext filterContext)
//    {
//        base.OnAuthorization(filterContext);
//        if (FailedRolesAuth)
//        {
//            filterContext.Result = new ViewResult { ViewName = "NotAuth" };
//        }
//    }
//}